<template>
  <div class="common-table">
    <el-table :data="data" v-bind="$attrs" v-on="$listeners" class="mb20" @selection-change="handleSelectionChange">
      <template v-for="column in finalColumns">
        <el-table-column v-if="$scopedSlots[column.prop]" v-bind="column" :key="column.prop">
          <template #default="scope">
            <slot :name="column.prop" v-bind="scope"></slot>
          </template>

          <template slot="header" v-if="column.showTip">
            {{ column.label }}
            <el-tooltip class="item" effect="dark" :content="column.tipContent" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </template>
        </el-table-column>

        <BaseColumn v-else :key="column.prop" :column="column" />
      </template>
    </el-table>

    <BasePagination :pagination="pagination" @change="handleChange" />
  </div>
</template>

<script>
import BaseColumn from './column'
import BasePagination from './pagination'

const defaultColumnOption = {
  align: 'center',
  showOverflowTooltip: true,
}

export default {
  name: 'BaseTable',
  inheritAttrs: false,
  components: {
    BaseColumn,
    BasePagination,
  },
  props: {
    data: Array,
    columns: Array,
    onChange: Function,
    columnOptions: Object,
    pagination: {
      type: [Object, Boolean],
      default: () => ({}),
    },
  },
  computed: {
    finalColumns() {
      const { columnOptions, columns } = this

      return columns.map(column => ({
        ...defaultColumnOption,
        ...columnOptions,
        ...column,
      }))
    },
  },

  methods: {
    handleChange(pagination) {
      if (this.onChange) {
        this.onChange(pagination)
      }

      this.$emit('change', pagination)
    },
    handleSelectionChange(val) {
      this.$emit('selectChange', val)
    },
  },
}
</script>
